package com.xinyin.aiqinhaiback.service.handStrategy;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.serotonin.modbus4j.exception.ErrorResponseException;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import com.xinyin.aiqinhaiback.common.Enum.ResultEnum;
import com.xinyin.aiqinhaiback.common.ResponseResult;
import com.xinyin.aiqinhaiback.exception.MyException;
import com.xinyin.aiqinhaiback.modbus.Modbus4jWriteUtils;
import com.xinyin.aiqinhaiback.model.entity.Param;
import com.xinyin.aiqinhaiback.service.HandleStrategy;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
@Component
public class StrategyContext {
	private HandleStrategy handleStrategy;
	public void setReceiptHandleStrategy(HandleStrategy handleStrategy) {
		if (handleStrategy==null){
			throw new MyException(ResultEnum.NOFINDTYPE);
		}
		this.handleStrategy = handleStrategy;
	}

	//调用策略类中的方法
	public ResponseResult updateConfig(Param param){
		if(param != null && StringUtils.isNotEmpty(param.getIp())){
			Modbus4jWriteUtils writeUtils = new Modbus4jWriteUtils(param.getIp());
			try {
				writeUtils.write(param.getModbus(),param.getValue());
			} catch (Exception e) {
				throw new MyException(ResultEnum.WIRTEFAIL);
			}
		}
		return new ResponseResult();
	}

	public ResponseResult<List<Map<String, Object>>> selectConfig(Param param) throws Exception {
		if(param != null){
			return handleStrategy.selectConfig(param);
		}
		return new ResponseResult();
	}


}
